//
//  GWCommentInputView.m
//  YY键盘
//
//  Created by hu on 16/5/30.
//  Copyright © 2016年 hu. All rights reserved.
//
#define KMinHeight 45.0f
#define KYYKeyBoard [YYKeyboardManager defaultManager]
#define kFunctionViewHeight 210.f
#define SCREEN_Height_HU [[UIScreen mainScreen]bounds].size.height
#define KTEXTPLACEHOLDER @"评论...";

#import "GWCommentInputView.h"
#import "YYKeyboardManager.h"
#import "Masonry.h"
#import "HUFaceView.h"
#import "HPGrowingTextView.h"

@interface GWCommentInputView ()<YYKeyboardObserver,HPGrowingTextViewDelegate,HUChatFaceViewDelegate>
{
    CGFloat _changeFrontHeight;                   ///< 变化前的高度
}

@property (nonatomic, weak  ) UIView            * superView;/**< 父视图 */
@property (nonatomic, assign) CGRect            superFrame;

@property (nonatomic, strong) UIButton          *sendButton;///< 发送按钮
@property (strong, nonatomic) UIButton          *faceButton;/**< 表情按钮 */

@property (strong, nonatomic) HPGrowingTextView *textView;/**< 输入框*/
@property (strong, nonatomic) HUFaceView        *faceView;/**< 表情视图*/


@property (copy, nonatomic  ) NSString          *inputText;
@property (nonatomic, assign) CGRect             lastFrame;

@property (nonatomic, assign) CGRect tmpFrame;

@end


@implementation GWCommentInputView

+ (instancetype)shareManager {
    static GWCommentInputView* object = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        object = [[self allocWithZone:NULL]init];
        UIWindow* window = [[[UIApplication sharedApplication]delegate]window];
        object.superFrame = window.frame;
        object.superView = window;
        object.isFirstResponse = NO;
        [KYYKeyBoard addObserver:object];
        [object setup];
    });
    return object;
}
- (void)show {
    UIWindow* window = [[[UIApplication sharedApplication] delegate]window];
    [window makeKeyAndVisible];
    [window addSubview:self];
    self.alpha = 0;
    self.faceView.alpha = 0;
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 1;
        self.faceView.alpha = 1;
    }];
}

- (void)hide {
    [self endInputing];
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0;
        self.faceView.alpha = 0;
    }];
}
- (void)dealloc {
    [KYYKeyBoard removeObserver:self];
    [self removeFromSuperview];
    [self.faceView removeFromSuperview];
}
- (void)endInputing {
    if (self.isFirstResponse) {
        [self showViewWithType:GWFunctionViewShowNothing];
        //结束编辑
    }
    //放弃第一响应者
    self.isFirstResponse = NO;
    [self.textView endEditing:YES];
}

#pragma mark YYKeyBoard 键盘代理事件
- (void)keyboardChangedWithTransition:(YYKeyboardTransition)transition {
    CGRect kbFrame = [KYYKeyBoard convertRect:transition.toFrame toView:self.superView];
    __weak typeof(self)weakSelf = self;
    //键盘消失
    if (!transition.toVisible) {
        self.isFirstResponse = YES;
        [UIView animateWithDuration:transition.animationDuration delay:0 options:transition.animationOption animations:^{
            if (weakSelf.faceButton.selected ) {
                return ;
            }
            CGRect textframe = self.frame;
            textframe.origin.y = self.superFrame.size.height - self.frame.size.height;
            
            
            [self setFrame:textframe];
        } completion:nil];
    }
    //键盘出现
    else{
        
        [UIView animateWithDuration:transition.animationDuration delay:0 options:transition.animationOption animations:^{
            CGRect textframe = weakSelf.frame;
            if (_changeFrontHeight) {
                textframe.size.height = _changeFrontHeight;
                _changeFrontHeight = 0;
            }
            self.isFirstResponse = YES ;
            textframe.origin.y = SCREEN_HEIGHT - kbFrame.size.height - textframe.size.height ;
            [weakSelf setFrame:textframe animated:NO toType:GWFunctionViewShowKeyboard];
            weakSelf.faceButton.selected = NO;
        } completion:nil];
    }
}
//初始self的frame
- (void)initTextViewFrameWithtoType:(GWFunctionViewShowType)toType{
    CGRect textframe = self.frame;

    
    textframe.origin.y = SCREEN_HEIGHT - self.frame.size.height;
    
    
    [self setFrame:textframe animated:YES toType:toType];
    
}
- (void)setup {
    [self updateSelfFrame];
    //表情按钮 暂时不需要
//    [self addSubview:self.faceButton];
    [self addSubview:self.textView];
    [self addSubview:self.sendButton];
}
- (void)updateSelfFrame {
    self.backgroundColor = [UIColor whiteColor];
    
    self.frame = CGRectMake(0, SCREEN_Height_HU - KMinHeight  ,  SCREEN_Width_HU, KMinHeight);
    self.tmpFrame = self.frame;
    UIImageView *topLine = [[UIImageView alloc] init];
    topLine.backgroundColor = [UIColor colorWithRed:184/255.0f green:184/255.0f blue:184/255.0f alpha:1.0f];
    [self addSubview:topLine];
    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.right.equalTo(self.mas_right);
        make.top.equalTo(self.mas_top);
        make.height.mas_equalTo(@.5f);
    }];
}
#pragma mark 更新UI布局
- (void)updateConstraints{
    [super updateConstraints];
    
    //表情按钮 暂时不需要
//    [self.faceButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.mas_right).with.offset(-10);
//        make.bottom.equalTo(self.mas_bottom).with.offset(-6);
//        //        make.width.equalTo(self.faceButton.mas_height);
//        make.width.mas_equalTo(32);
//        make.height.mas_equalTo(32);
//    }];
    
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mas_right).with.offset(-10);
        make.bottom.equalTo(self.mas_bottom).with.offset(-6);
        //        make.width.equalTo(self.faceButton.mas_height);
        make.width.mas_equalTo(42);
        make.height.mas_equalTo(32);
    }];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).with.offset(10);
        make.right.equalTo(self.sendButton.mas_left).with.offset(-10);
        make.top.equalTo(self.mas_top).with.offset(4);
        make.bottom.equalTo(self.mas_bottom).with.offset(-4);
    }];
    
 
}
#pragma mark button点击事件
- (void)buttonAction:(UIButton *)button{
    self.inputText = self.textView.text;
    GWFunctionViewShowType showType = button.tag;
    
    //更改对应按钮的状态
    if (button == self.faceButton) {
        [self.faceButton setSelected:!self.faceButton.selected];

    }
    
    if (!button.selected) {
        showType = GWFunctionViewShowKeyboard;
        [self.textView becomeFirstResponder];
    }else {
        [self.textView resignFirstResponder];
    }
    [self showViewWithType:showType];
}
- (void)showViewWithType:(GWFunctionViewShowType)showType{
    //显示对应的View
   [self showFaceView:showType  == GWFunctionViewShowFace && self.faceButton.selected];
    
    self.inputText = self.textView.text;
    
    switch (showType) {
            
        case GWFunctionViewShowNothing:{
            self.isFirstResponse = NO;
            self.showType = GWFunctionViewShowNothing;
            [self initTextViewFrameWithtoType:GWFunctionViewShowNothing];
            break;
        }
        case GWFunctionViewShowVoice:{
            self.isFirstResponse = NO;
            self.showType = GWFunctionViewShowVoice;
            [self initTextViewFrameWithtoType:GWFunctionViewShowVoice];
            break;
        }
        case GWFunctionViewShowMore:{
            self.isFirstResponse = YES;
            self.showType = GWFunctionViewShowMore;
            break;
        }
        case GWFunctionViewShowFace:{
            self.isFirstResponse = YES;
            self.showType = GWFunctionViewShowFace;
            break;
        }
        case GWFunctionViewShowKeyboard:{
            self.isFirstResponse = YES;
            self.showType = GWFunctionViewShowKeyboard;
            break;
        }
        default:
            break;
    }
    
}
#pragma mark  切换输入状态 输入语音 表情 图片

- (void)showFaceView:(BOOL)show{
    __weak typeof(self)weakSelf = self ;
    
    if (show) {
        //成为第一响应者
        self.isFirstResponse = YES;
        [self.superView addSubview:self.faceView];
        CGRect changeFrame = self.frame;
        changeFrame.origin.y = SCREEN_HEIGHT - _faceView.frame.size.height - changeFrame.size.height;
        [UIView animateWithDuration:0.25 delay:0 options:7 animations:^{
            [weakSelf setFrame:changeFrame animated:NO toType:GWFunctionViewShowFace];
            _faceView.frame = CGRectMake(0, CGRectGetMaxY(weakSelf.frame), SCREEN_Width_HU, _faceView.frame.size.height);
        } completion:nil];
        //正在编辑
        
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            _faceView.frame = CGRectMake(0, self.superFrame.size.height, SCREEN_Width_HU, _faceView.frame.size.height);
        } completion:^(BOOL finished) {
            [weakSelf.faceView removeFromSuperview];
        }];
        //结束编辑
        
    }
}
#pragma mark - HUFaceView 代理方法
- (void)faceViewSendFace:(NSString *)faceName{
    if ([faceName isEqualToString:@"[删除]"]) {
        [self growingTextView:self.textView shouldChangeTextInRange:NSMakeRange(self.textView.text.length - 1, 1) replacementText:@""];
    }else if ([faceName isEqualToString:@"发送"]){
        NSString *text = self.textView.text;
        if (!text || text.length == 0) {
            return;
        }
        [self sendTextMessage:_textView.text];
        self.inputText = @"";
        self.textView.text = @"";
        //        [self showViewWithType:GWFunctionViewShowFace];
    }else{
        self.textView.text = [self.textView.text stringByAppendingString:faceName];
    }
}
#pragma mark - 输入框代理方法
- (BOOL)growingTextView:(HPGrowingTextView *)growingTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [self sendTextMessage:growingTextView.text];
        return NO;
    }else if (text.length == 0){
        //判断删除的文字是否符合表情文字规则
        NSString *deleteText = [growingTextView.text substringWithRange:range];
        if ([deleteText isEqualToString:@"]"]) {
            NSUInteger location = range.location;
            NSUInteger length = range.length;
            NSString *subText;
            while (YES) {
                if (location == 0) {
                    return YES;
                }
                location -- ;
                length ++ ;
                subText = [growingTextView.text substringWithRange:NSMakeRange(location, length)];
                if (([subText hasPrefix:@"["] && [subText hasSuffix:@"]"])) {
                    break;
                }
            }
            growingTextView.text = [growingTextView.text stringByReplacingCharactersInRange:NSMakeRange(location, length) withString:@""];
            [growingTextView setSelectedRange:NSMakeRange(location, 0)];
            //            [self textViewDidChange:self.textView];
            return NO;
        }
    }
    return YES;
}
/**
 *  发送普通的文本信息,通知代理
 *
 *  @param text 发送的文本信息
 */
- (void)sendTextMessage:(NSString *)text{
    if (!text || text.length == 0) {
        return;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendMessage:)]) {
        [self.delegate chatBar:self sendMessage:text];
    }
    self.inputText = @"";
    self.textView.text = @"";
    [self setFrame:CGRectMake(0, self.superFrame.size.height - KMinHeight - KYYKeyBoard.keyboardFrame.size.height, self.frame.size.width, KMinHeight) animated:NO toType:GWFunctionViewShowNothing];
    //    [self showViewWithType:GWFunctionViewShowNothing];
    [self endInputing];
}
- (void)sendClick {
    [self sendTextMessage:self.textView.text];
}

#pragma mark 键盘随着输入高度增高
- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height {
    self.isFirstResponse = YES;
    static float initValue = 36 ;
    float changeValue = height - initValue;
    if (changeValue > 0) {
        self.isGrow = YES;
    }else{
        self.isGrow = NO;
    }
    if (changeValue != 0) {
        CGRect viewFrame = self.frame;
        viewFrame.origin.y -= changeValue;
        viewFrame.size.height += changeValue;
        //        self.frame = viewFrame;
        //        [self setFrame:viewFrame animated:NO toType:GWFunctionViewShowKeyboard];
        [self setFrame:viewFrame];
        initValue = height;
        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarGrowingTextViewEditing:)]){
            [self.delegate chatBarGrowingTextViewEditing:changeValue];
        }
    }
    
}

#pragma mark SET && GET
- (HPGrowingTextView *)textView{
    if (!_textView) {
        _textView = [[HPGrowingTextView alloc] init];
        _textView.font = [UIFont systemFontOfSize:16.0f];
        _textView.placeholder = KTEXTPLACEHOLDER;
        _textView.delegate = self;
        _textView.layer.cornerRadius = 4.0f;
        _textView.layer.borderColor = [UIColor colorWithRed:204.0/255.0f green:204.0/255.0f blue:204.0/255.0f alpha:1.0f].CGColor;
        _textView.returnKeyType = UIReturnKeySend;
        _textView.layer.borderWidth = .5f;
        _textView.layer.masksToBounds = YES;
        [_textView.inputView addSubview:self.faceView];
    }
    return _textView;
}
- (UIButton *)sendButton{
    if (!_sendButton) {
        _sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _sendButton.bounds = CGRectMake(0, 0, 120, 40);
        _sendButton.layer.cornerRadius = 5;
        _sendButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
        _sendButton.backgroundColor = [UIColor colorWithRed:0 green:147/255. blue:1 alpha:1];
        [_sendButton addTarget:self action:@selector(sendClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendButton;
}
- (UIButton *)faceButton{
    if (!_faceButton) {
        _faceButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _faceButton.tag = GWFunctionViewShowFace;
        [_faceButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_face_normal"] forState:UIControlStateNormal];
        [_faceButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_input_normal"] forState:UIControlStateSelected];
        [_faceButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_faceButton sizeToFit];
    }
    return _faceButton;
}
- (HUFaceView *)faceView {
    if (!_faceView) {
        _faceView = [[HUFaceView alloc] initWithFrame:CGRectMake(0, self.superFrame.size.height, self.frame.size.width, kFunctionViewHeight)];
        _faceView.delegate = self ;
        _faceView.backgroundColor = self.backgroundColor ;
    }
    return _faceView;
}

- (void)setFrame:(CGRect)frame animated:(BOOL)animated toType:(GWFunctionViewShowType)toType{
    if (animated) {
        [UIView animateWithDuration:.3 animations:^{
            [self setFrame:frame];
        }];
    }else{
        [self setFrame:frame];
    }
    CGFloat changeHeight;
    changeHeight = self.frame.origin.y - self.tmpFrame.origin.y;
    if (changeHeight != 0 || (self.showType != toType)) {
        self.tmpFrame = self.frame;
        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarChangeHeight:toType:)]) {
            [self.delegate chatBarChangeHeight:changeHeight toType:toType];
            self.showType = toType;
        }
    }
    if (toType == GWFunctionViewShowKeyboard ||
        toType == GWFunctionViewShowFace ||
        toType == GWFunctionViewShowMore) {
        if (self.isFirstResponse) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarTextViewDidChangeEditing:)]){
                [self.delegate chatBarTextViewDidChangeEditing:self.textView];
                return;
            }
        }else{
            if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarTextViewDidBeginEditing:)]) {
                [self.delegate chatBarTextViewDidBeginEditing:self.textView];
                return;
            }
        }
        
    }else if (toType == GWFunctionViewShowVoice ||
              toType == GWFunctionViewShowNothing){
        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarTextViewDidEndEditing:)]) {
            [self.delegate chatBarTextViewDidEndEditing:self.textView];
            return;
        }
    }
}
@end
